package com.igl.talk.android.client.ide.activities;

import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.igl.talk.android.client.R;
import com.igl.talk.android.client.application.BaseApplication;
import com.igl.talk.android.client.core.service.Server;
import com.igl.talk.android.client.core.utils.InternetUtils;

/*
 * @author Adam Wieczorek 
 *
 * 16/03/2014
 *
 * All rights reserved.
 */
public class RegisterActivity extends BaseServiceBindingActivity {

    public static String USERNAME = "com.igl.talk.android.client.ide.activities.RegisterActivity.username";

    private static String LOG_TAG = RegisterActivity.class.getSimpleName() + ".class";

    private boolean userRegistered;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);

        final BaseApplication application = (BaseApplication)getApplication();

        if (application.isUserRegistered()) {
            goToMainView(false, null);
        }

        final EditText usernameField = (EditText)findViewById(R.id.usernameInputField);

        Button buttonRegister = (Button)findViewById(R.id.buttonRegister);
        buttonRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String username = usernameField.getText().toString();
                userRegistered = Server.INSTANCE.register(username);
                application.setUserRegistered(userRegistered);
                if (userRegistered) {
                   goToMainView(true, username);
                } else {
                    Toast.makeText(getApplicationContext(), getApplicationContext().getResources()
                            .getString(R.string.error_name_used, username), Toast.LENGTH_SHORT).show();
                }
            }
        });

        if (!InternetUtils.isInternetConnectionAvailable(getBaseContext())) {
            buttonRegister.setEnabled(false);
            Toast.makeText(getApplicationContext(), R.string.error_no_internet_connection, Toast.LENGTH_SHORT).show();
        }
    }

    private void goToMainView(boolean createNewTask, String username) {
        Intent intent = new Intent(RegisterActivity.this, MainViewActivity.class);
        if (createNewTask) {
            intent.putExtra(USERNAME, username);
        } else {
            intent.setAction(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
        }
        startActivity(intent);
    }
}